export const initSdpServer = io => {
  io.on('connection', socket => {
    onEvent(socket)
  })
}

const roomMap = new Map()

const onEvent = socket => {
  const { roomId, userId } = socket.request._query

  // 用户加入
  !roomMap.has(roomId)
    ? roomMap.set(roomId, 1)
    : roomMap.set(roomId, roomMap.get(roomId) + 1)

  if (roomMap.get(roomId) > 2) {
    socket.emit('room-full')
    roomMap.set(roomId, roomMap.get(roomId) - 1)
    console.log('加入失败，当前房间人数已满', roomMap.get(roomId) + '人')
    return
  }
  socket.join(roomId)
  socket.emit('people-count-msg', roomMap.get(roomId))
  socket.to('roomId').emit('people-count-msg', roomMap.get(roomId))

  console.log(
    userId + '加入' + roomId + '号房间，当前房间人数：' + roomMap.get(roomId)
  )

  // 用户离开
  socket.on('disconnect', () => {
    socket.to(roomId).emit('client_leave', userId + ':leave')
    roomMap.set(roomId, roomMap.get(roomId) - 1)

    console.log(
      userId + '离开' + roomId + '号房间, 当前房间人数：' + roomMap.get(roomId)
    )
  })

  // 媒体协商
  socket.on('offer-sdp-msg', offerSDP => {
    socket.to(roomId).emit('offer-sdp-msg', offerSDP)
  })

  socket.on('answer-sdp-msg', answerSDP => {
    socket.to(roomId).emit('answer-sdp-msg', answerSDP)
  })

  // 网络协商
  socket.on('candidate-msg', candidate => {
    socket.to(roomId).emit('candidate-msg', candidate)
  })
}
